package com.sooncode.project.focusservice.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sooncode.project.core.finder.Finder;
import com.sooncode.project.core.finder.OType;
import com.sooncode.project.core.finder.Page;
import com.sooncode.project.core.finder.Sort;
import com.sooncode.project.core.model.DomainException;
import com.sooncode.project.core.monitor.Monitor;
import com.sooncode.project.core.session.DomainSession;
import com.sooncode.project.core.session.SessionManager;
import com.sooncode.project.focusservice.model.*;
import com.sooncode.project.springcloudcommon.model.AuthInfo;
import com.sooncode.project.springcloudcommon.utils.DateUtils;
import com.sooncode.project.springcloudcommon.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MemberService {
    Monitor monitor = Monitor.New();

    public MemberService() {
        monitor.ListenEntity(Fee.class).add((en) -> {
            getById(((Fee) en.getTargetEntity()).getMemberId()).totalMoney();
        });
        monitor.ListenEntity(Fee.class).modify((en) -> {
            getById(((Fee) en.getTargetEntity()).getMemberId()).totalMoney();
        });
        monitor.ListenEntity(Fee.class).delete((en) -> {
            getById(((Fee) en.getTargetEntity()).getMemberId()).totalMoney();
        });
    }

    public boolean add(Map map) {
        DomainSession session = new DomainSession();
        Member member = new Member();
        session.add(member);
        try {
            member.add(map);
            member.updateAge();
            session.commit();
        } catch (Exception ex) {
            session.rollback();
            throw ex;
        }
        return true;
    }

    public boolean modify(String id, Map map) {
        DomainSession session = new DomainSession();
        Member member = getById(id);
        session.add(member);
        try {
            member.modify(map);
            member.updateAge();
            session.commit();
        } catch (Exception ex) {
            session.rollback();
            throw ex;
        }
        return true;
    }

    public boolean delete(String id) {
        Member member = getById(id);
        member.delete();
        return true;
    }

    public Page<Member> getPageList(int pageSize, int pageIndex, Map map) {
        Object orgName = map.get("orgName");
        map.remove("orgName");
        Object name=map.get("name");
        map.remove("name");
        Object salesPerson=map.get("salesPerson");
        map.remove("salesPerson");
        return new Finder<>(Member.class)
                .byField("orgName", orgName, OType.contains)
                .and("name",name,OType.contains)
                .and("salesPerson",salesPerson,OType.contains)
                .and(map)
                .page(pageSize, pageIndex, Sort.DESC("createDate"));
    }

    public Member getById(String id) {
        return new Finder<>(Member.class).byId(id);
    }

    public List<Member> getMemberList(Map<String,Object> params) {
        AuthInfo authInfo = UserUtils.getCurrentUser();
        Organization org = new Finder<>(Organization.class)
                .byField("accountId", authInfo.getUserid()).first();
        if (org == null) throw new DomainException("机构不存在");
        return new Finder<>(Member.class)
                .byField("orgId", org.getId())
            .and(params).list(Sort.DESC("member_no"));
    }

    public Page<Member> getPageListForDevice(int pageSize, int pageIndex, Map map) {
        AuthInfo authInfo = UserUtils.getCurrentUser();
        Organization org = new Finder<>(Organization.class)
                .byField("accountId", authInfo.getUserid())
                .first();
        String memberNo="";
        if(map.containsKey("memberNo"))
            memberNo=map.get("memberNo").toString();
        map.remove("memberNo");
        return new Finder<>(Member.class)
                .byField("orgId", org.getId())
                .and("memberNo", memberNo,OType.eq)
                .and(map)
                .page(pageSize, pageIndex, Sort.DESC("createDate"));
    }

    public boolean modifyForDevice(String id, Map map) {
        AuthInfo authInfo = UserUtils.getCurrentUser();
        Organization org = new Finder<>(Organization.class)
                .byField("accountId", authInfo.getUserid())
                .first();
        map.put("orgId", org.getId());
        return modify(id, map);
    }

    public boolean addForDevice(Map map) {
        AuthInfo authInfo = UserUtils.getCurrentUser();
        Organization org = new Finder<>(Organization.class)
                .byField("accountId", authInfo.getUserid())
                .first();
        map.put("orgId", org.getId());
        return add(map);
    }

    //会员类型与渠道
    public boolean addChannel(Map map) {
        Channel channel = new Channel();
        channel.add(map);
        return true;
    }

    public boolean modifyChannel(String id, Map map) {
        Channel channel = new Finder<>(Channel.class)
                .byId(id);
        channel.modify(map);
        return true;
    }

    public boolean deleteChannel(String id) {
        Channel channel = new Finder<>(Channel.class)
                .byId(id);
        channel.delete();
        return true;
    }

    public List<Channel> getChannelList() {
        return new Finder<>(Channel.class)
                .list();
    }

    public boolean addMemberStatus(Map map) {
        MemberStatus memberStatus = new MemberStatus();
        memberStatus.add(map);
        return true;
    }

    public boolean modifyMemberStatus(String id, Map map) {
        MemberStatus memberStatus = new Finder<>(MemberStatus.class)
                .byId(id);
        memberStatus.modify(map);
        return true;
    }

    public boolean deleteMemberStatus(String id) {
        MemberStatus memberStatus = new Finder<>(MemberStatus.class)
                .byId(id);
        memberStatus.delete();
        return true;
    }

    public List<MemberStatus> getMemberStatusList() {
        return new Finder<>(MemberStatus.class)
                .list();
    }

    public boolean importMembersForDevice(String text) {
        JSONObject obj = (JSONObject) JSON.parse(text);
        JSONArray array = (JSONArray) obj.get("Rows");
        AuthInfo authInfo = UserUtils.getCurrentUser();
        Organization org = new Finder<>(Organization.class)
                .byField("accountId", authInfo.getUserid())
                .first();
        DomainSession session = new DomainSession();
        try {
            for (Object item : array) {
                JSONObject object = (JSONObject) item;
                Member tm = new Finder<>(Member.class)
                        .byField("studId", object.getString("StudId"))
                        .first();
                if (tm != null) continue;
                Member member = new Member();
                session.add(member);
                member.setOrgId(org.getId());
                member.setStudId(object.getString("StudId"));
                member.setName(object.getString("StudName"));
                member.setSex(object.getString("StudSex"));
                member.setAge(object.getString("StudAgeYear"));
                Date date = object.getDate("StudBirthday");
                member.setBirth(DateUtils.format(date, "yyyy-MM-dd"));
                member.setParent_name(object.getString("StudRelaName"));
                member.setPhone(object.getString("StudTelephone"));
                member.setChannel("导入");
                member.add(org);
            }
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
            return false;
        }
        return true;
    }
    public boolean generatePadCode(String id){
        Member member=new Finder<>(Member.class).byId(id);
        member.generatePadCode();
        return true;
    }

    public boolean importMembers(MultipartFile[] files,String orgId) {
        DomainSession session = new DomainSession();
        try{
            EasyExcel.read(files[0].getInputStream(), MemberImport.class,new MemberImport(orgId,session)).sheet().doRead();
            session.commit();
        }catch (RuntimeException ex){
            ex.printStackTrace();
            session.rollback();
            throw new DomainException(ex.getMessage());
        }
        catch (IOException ex){
            ex.printStackTrace();
            session.rollback();
            throw new DomainException("解析文件错误");
        }
        return true;
    }
}
